<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name = "description" content = "Online tool to create code for polyline and polygon to Google Maps v3 (version 3)"/>
<title>Tool for Google Maps v3 (version 3)</title>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="json2.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
//<![CDATA[

// This application is provided by Kjell Scharning
//  Licensed under the Apache License, Version 2.0;
//  http://www.apache.org/licenses/LICENSE-2.0

function gob(e){if(typeof(e)=='object')return(e);if(document.getElementById)return(document.getElementById(e));return(eval(e))}
var map;
var polyShape;
var markerShape;
//var oldDirMarkers = [];
//var tmpPolyLine;
var drawnShapes = [];
var holeShapes = [];
var startMarker;
var nemarker;
var tinyMarker;
var markers = [];
var midmarkers = [];
//var markerlistener1;
//var markerlistener2;
var rectangle;
var circle;
var southWest;
var northEast;
var centerPoint;
var radiusPoint;
var calc;
var startpoint;
var adder = 0;
var dirpointstart = null;
//var dirpointend = 0;
var dirline;
var waypts = [];
//var waypots = [];
var polyPoints = [];
var pointsArray = [];
var markersArray = [];
var addresssArray = [];
var pointsArrayKml = [];
var markersArrayKml = [];
var toolID = 1;
var codeID = 1;
var shapeId = 0;
var step = 0;
var plmcur = 0;
var lcur = 0;
var pcur = 0;
//var rcur = 0;
var ccur = 0;
var mcur = 0;
var outerPoints = [];
var holePolyArray = [];
var outerShape;
var anotherhole = false;
//var it;
var outerArray = [];
var innerArray = [];
var innerArrays = [];
var outerArrayKml = [];
var innerArrayKml = [];
var innerArraysKml = [];
var placemarks = [];
//var mylistener;
var editing = false;
var notext = false;
var textsignal = 0;
var kmlcode = "";
var javacode = "";
var polylineDecColorCur = "255,0,0";
var polygonDecColorCur = "255,0,0";
var docuname = "My document";
var docudesc = "Content";
var polylinestyles = [];
var polygonstyles = [];
//var rectanglestyles = [];
var circlestyles = [];
var markerstyles = [];
var geocoder; // = new google.maps.Geocoder();
//var startLocation;
var endLocation;
//var dircount;
var dircountstart;
var firstdirclick = 0;
var dirmarknum = 1;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var directionsYes = 0;
var destinations = [];
var removedirectionleg = 0;
//var currentDirections = null;
//var oldpoint = null;
var prevpoint;
var prevnumber;
var infowindow = new google.maps.InfoWindow();//({size: new google.maps.Size(150,50)});
var tmpPolyLine = new google.maps.Polyline({
    strokeColor: "#00FF00",
    strokeOpacity: 0.8,
    strokeWeight: 2
});
var tinyIcon = new google.maps.MarkerImage(
    'marker_20_red.png',
    new google.maps.Size(12,20),
    new google.maps.Point(0,0),
    new google.maps.Point(6,16)
);
var imageNormal = new google.maps.MarkerImage(
	"square.png",
	new google.maps.Size(11, 11),
	new google.maps.Point(0, 0),
	new google.maps.Point(6, 6)
);
var imageHover = new google.maps.MarkerImage(
	"square_over.png",
	new google.maps.Size(11, 11),
	new google.maps.Point(0, 0),
	new google.maps.Point(6, 6)
);
var imageNormalMidpoint = new google.maps.MarkerImage(
	"square_transparent.png",
	new google.maps.Size(11, 11),
	new google.maps.Point(0, 0),
	new google.maps.Point(6, 6)
);

function polystyle() {
    this.name = "Lump";
    this.kmlcolor = "CD0000FF";
    this.kmlfill = "9AFF0000";
    this.color = "#FF0000";
    this.fill = "#0000FF";
    this.width = 2;
    this.lineopac = 0.8;
    this.fillopac = 0.6;
}
function linestyle() {
    this.name = "Path";
    this.kmlcolor = "FF0000FF";
    this.color = "#FF0000";
    this.width = 3;
    this.lineopac = 1;
}
function circstyle() {
    this.name = "Circ";
    this.color = "#FF0000";
    this.fill = "#0000FF";
    this.width = 2;
    this.lineopac = 0.8;
    this.fillopac = 0.6;
}
function markerstyleobject() {
    this.name = "markerstyle";
    this.icon = "http://maps.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png";
}
function placemarkobject() {
    this.name = "NAME";
    this.desc = "YES";
    this.style = "Path";
    this.stylecur = 0;
    this.tess = 1;
    this.alt = "clampToGround";
    this.plmtext = ""; // KLM text from <Placemark> to </Placemark>
    this.jstext = "";
    this.jscode = [];
    this.kmlcode = []; // coordinatepairs lng lat
    this.kmlholecode = []; // coordinatepairs lng lat
    this.poly = "pl";
    this.shape = null;
    this.point = null;
    this.toolID = 1;
    this.hole = 0;
    this.ID = 0;
}
function createplacemarkobject() {
    var thisplacemark = new placemarkobject();
    placemarks.push(thisplacemark);
}
function createpolygonstyleobject() {
    var polygonstyle = new polystyle();
    polygonstyles.push(polygonstyle);
}
function createlinestyleobject() {
    var polylinestyle = new linestyle();
    polylinestyles.push(polylinestyle);
}
function createcirclestyleobject() {
    var cirstyle = new circstyle();
    circlestyles.push(cirstyle);
}
function createmarkerstyleobject() {
    var thisstyle = new markerstyleobject();
    markerstyles.push(thisstyle);
}
function preparePolyline(){
    var polyOptions = {
        path: polyPoints,
        strokeColor: polylinestyles[lcur].color,
        strokeOpacity: polylinestyles[lcur].lineopac,
        strokeWeight: polylinestyles[lcur].width};
    polyShape = new google.maps.Polyline(polyOptions);
    polyShape.setMap(map);
    /*var tmpPolyOptions = {
    	strokeColor: polylinestyles[lcur].color,
    	strokeOpacity: polylinestyles[lcur].lineopac,
    	strokeWeight: polylinestyles[lcur].width
    };
    tmpPolyLine = new google.maps.Polyline(tmpPolyOptions);
    tmpPolyLine.setMap(map);*/
}

function activateMarker() {
    markerShape = new google.maps.Marker({
        map: map,
        icon: markerstyles[mcur].icon
    });
}
function initmap(){
    geocoder = new google.maps.Geocoder();
	if(google.loader.ClientLocation.latitude && google.loader.ClientLocation.longitude){
		var latlng = new google.maps.LatLng(google.loader.ClientLocation.latitude ,google.loader.ClientLocation.longitude);
	}
	else{
		var latlng = new google.maps.LatLng(59.914063, 10.737874);//(45.0,7.0);//45.074723, 7.656433
	}
	
    var myOptions = {
        zoom: 12,
        center: latlng,
        draggableCursor: 'default',
        draggingCursor: 'pointer',
        scaleControl: true,
        mapTypeControl: true,
        mapTypeControlOptions:{style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        styles: [{featureType: 'poi', stylers: [{visibility: 'off'}]}],
        streetViewControl: false};
    map = new google.maps.Map(gob('map_canvas'),myOptions);
    //var myStyle = [{featureType: 'poi', stylers: [{visibility: 'off'}]}];
    //map.setOptions({styles: myStyle}); // styles and stylers are arrays
    polyPoints = new google.maps.MVCArray(); // collects coordinates
    tmpPolyLine.setMap(map);
    createplacemarkobject();
    createlinestyleobject();
    createpolygonstyleobject();
    createcirclestyleobject();
    createmarkerstyleobject();
    preparePolyline(); // create a Polyline object

	//Beim Anschauen der Karte wird der Listener nicht aktiviert ToDo
    google.maps.event.addListener(map, 'click', addLatLng);
	
    //Karte muss nuoch geladen werden, falls man diese anzeigen will ToDo
    load_strecke();
}


function addLatLng(point){
    if(directionsYes == 1) {
        drawDirections(point.latLng);
        return;
    }
    if(plmcur != placemarks.length-1) {
        nextshape();
    }

    // Rectangle and circle can't collect points with getPath. solved by letting Polyline collect the points and then erase Polyline
    polyPoints = polyShape.getPath();
    // This codeline does the drawing on the map
    polyPoints.insertAt(polyPoints.length, point.latLng); // or: polyPoints.push(point.latLng)
    if(polyPoints.length == 1) {
        startpoint = point.latLng;
        placemarks[plmcur].point = startpoint; // stored because it's to be used when the shape is clicked on as a stored shape
        setstartMarker(startpoint);
        if(toolID == 5) {
            drawMarkers(startpoint);
        }
    }
    //if(polyPoints.length == 2 && toolID == 3) createrectangle(point);
    //if(polyPoints.length == 2 && toolID == 4) createcircle(point);
    /*if(toolID == 1 || toolID == 2) { // if polyline or polygon
        var stringtobesaved = point.latLng.lat().toFixed(6) + ',' + point.latLng.lng().toFixed(6);
        var kmlstringtobesaved = point.latLng.lng().toFixed(6) + ',' + point.latLng.lat().toFixed(6);
        //Cursor position, when inside polyShape, is registered with this listener
        cursorposition(polyShape);
        if(adder == 0) { //shape with no hole
            pointsArray.push(stringtobesaved); // collect textstring for presentation in textarea
            pointsArrayKml.push(kmlstringtobesaved); // collect textstring for presentation in textarea
            //if(polyPoints.length == 1 && toolID == 2) closethis('polygonstuff');
            //if(codeID == 1 && toolID == 1) logCode1(); // write kml for polyline
            //if(codeID == 1 && toolID == 2) logCode2(); // write kml for polygon
            //if(codeID == 2) logCode4(); // write Google javascript
        }
        if(adder == 1) { // adder is increased in function holecreator
            outerArray.push(stringtobesaved);
            outerArrayKml.push(kmlstringtobesaved);
        }
        if(adder == 2) {
            innerArray.push(stringtobesaved);
            innerArrayKml.push(kmlstringtobesaved);
        }
    }*/
	editlines();
	editlines();
}
function setstartMarker(point){
    startMarker = new google.maps.Marker({
        position: point,
        map: map});
    startMarker.setTitle("#" + polyPoints.length);
}
// calculate distance between two coordinates
function distance(lat1,lon1,lat2,lon2) {
    var R = 6371000; // earth's radius in meters
    var dLat = (lat2-lat1) * Math.PI / 180;
    var dLon = (lon2-lon1) * Math.PI / 180;
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
    Math.sin(dLon/2) * Math.sin(dLon/2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d = R * c;
    return d;
}

function drawMarkers(point) {
    if(startMarker) startMarker.setMap(null);
    if(polyShape) polyShape.setMap(null);
    var id = plmcur;
    placemarks[plmcur].jscode = point.lat().toFixed(6) + ',' + point.lng().toFixed(6);
    placemarks[plmcur].kmlcode = point.lng().toFixed(6) + ',' + point.lat().toFixed(6);
    activateMarker();
    markerShape.setPosition(point);
    var marker = markerShape;
    tinyMarker = new google.maps.Marker({
        position: placemarks[plmcur].point,
        map: map,
        icon: tinyIcon
    });
    google.maps.event.addListener(marker, 'click', function(event){
        plmcur = id;
        markerShape = marker;
        var html = "<b>" + placemarks[plmcur].name + "</b> <br/>" + placemarks[plmcur].desc;
        infowindow.setContent(html);
        if(tinyMarker) tinyMarker.setMap(null);
        tinyMarker = new google.maps.Marker({
            position: placemarks[plmcur].point,
            map: map,
            icon: tinyIcon
        });
        if(toolID != 5) toolID = gob('toolchoice').value = 5;
        if(codeID == 1)logCode9();
        if(codeID == 2)logCode8();
        infowindow.open(map,marker);
    });
    drawnShapes.push(markerShape);
    if(codeID == 2) logCode8();
    if(codeID == 1) logCode9();
}
//}
// Called from deleteLastPoint() initiated by click on button
function undo() {
    if(drawnShapes.length > 1) {
        drawnShapes[drawnShapes.length-1].setMap(null);
        destinations.pop();
        var point = destinations[destinations.length-1];
        //oldpoint = point;
        waypts.pop();
        var request = {
            origin: dirpointstart,
            destination: point,
            waypoints: waypts,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        placemarks.pop();
        markersArray.pop();
        markersArrayKml.pop();
        addresssArray.pop();
        //drawnShapes = [];
        firstdirclick = firstdirclick-1;
        step = step-1;
        dirmarknum = dirmarknum-1;
        plmcur = plmcur-1;
        removedirectionleg = 1;
        calcRoute(request);
    }
}


function setTool(){
    if(polyPoints.length == 0 && kmlcode == "" && javacode == "") {
        newstart();
    }else{
        if(toolID == 1){ // polyline
            // change to polyline draw mode not allowed
            if(outerArray.length > 0) { //indicates polygon with hole
                toolID = 2;
                nextshape();
                toolID = 1;
                newstart();
                return;
            }
            if(rectangle) {
                toolID = 3;
                nextshape();
                toolID = 1;
                newstart();
                return;
            }
            if(circle) {
                toolID = 4;
                nextshape();
                toolID = 1;
                newstart();
                return;
            }
            if(markerShape) {
                toolID = 5;
                nextshape();
                toolID = 1;
                newstart();
                return;
            }
            if(directionsYes == 1) {
                toolID = 6;
                nextshape();
                directionsYes = 0;
                toolID = 1;
                newstart();
                return;
            }
            placemarks[plmcur].style = polylinestyles[polylinestyles.length-1].name;
            placemarks[plmcur].stylecur = polylinestyles.length-1;
            if(polyShape) polyShape.setMap(null);
            preparePolyline(); //if a polygon exists, it will be redrawn as polylines
            //if(codeID == 1) logCode1(); // KML
            //if(codeID == 2) logCode4(); // Javascipt
        }
    }
}
function increaseplmcur() {
    if(placemarks[plmcur].plmtext != "") {
        if(polyShape && directionsYes == 0) {
            placemarks[plmcur].shape = polyShape;
            if(toolID==1 || toolID==2 || toolID==3) addpolyShapelistener();
            createplacemarkobject();
            plmcur = placemarks.length -1;
        }
        if(markerShape) {
            placemarks[plmcur].shape = markerShape;
            createplacemarkobject();
            plmcur = placemarks.length -1;
        }
    }
}
function newstart() {
    polyPoints = [];
    outerPoints = [];
    pointsArray = [];
    markersArray = [];
    pointsArrayKml = [];
    markersArrayKml = [];
    addresssArray = [];
    outerArray = [];
    innerArray = [];
    outerArrayKml = [];
    innerArrayKml = [];
    holePolyArray = [];
    innerArrays = [];
    innerArraysKml = [];
    waypts = [];
    destinations = [];
    adder = 0;
    dirpointstart = null;
    dirline = null;
    firstdirclick = 0;
    //dirmarknum = 1;
    step = 0;
    if(directionsYes == 1 && toolID != 6) directionsYes = 0;
    closethis('polylineoptions');
    closethis('polygonoptions');
    closethis('circleoptions');
    if(toolID != 2) closethis('polygonstuff');
    if(directionsDisplay) directionsDisplay.setMap(null);
    if(startMarker) startMarker.setMap(null);
    if(nemarker) nemarker.setMap(null);
    if(tinyMarker) tinyMarker.setMap(null);
    if(toolID == 1) {
        placemarks[plmcur].style = polylinestyles[polylinestyles.length-1].name;
        placemarks[plmcur].stylecur = polylinestyles.length-1;
        preparePolyline();
        polylineintroduction();
    }
    if(toolID == 2){
        showthis('polygonstuff');
        gob('stepdiv').innerHTML = "Step 0";
        placemarks[plmcur].style = polygonstyles[polygonstyles.length-1].name;
        placemarks[plmcur].stylecur = polygonstyles.length-1;
        preparePolygon();
        polygonintroduction();
    }
    if(toolID == 3) {
        placemarks[plmcur].style = polygonstyles[polygonstyles.length-1].name;
        placemarks[plmcur].stylecur = polygonstyles.length-1;
        preparePolyline(); // use Polyline to collect clicked point
        activateRectangle();
        rectangleintroduction();
    }
    if(toolID == 4) {
        placemarks[plmcur].style = circlestyles[circlestyles.length-1].name;
        placemarks[plmcur].stylecur = circlestyles.length-1;
        preparePolyline(); // use Polyline to collect clicked point
        activateCircle();
        circleintroduction();
        codeID = gob('codechoice').value = 2; // javascript, no KML for circle
    }
    if(toolID == 5) {
        placemarks[plmcur].style = markerstyles[markerstyles.length-1].name;
        placemarks[plmcur].stylecur = markerstyles.length-1;
        preparePolyline();
        markerintroduction();
    }
    if(toolID == 6){
        directionsYes = 1;
        /*if(dirline != null) {
            placemarks[plmcur].style = placemarks[dirline].style;
            placemarks[plmcur].stylecur = placemarks[dirline].stylecur;
        }else{*/
            placemarks[plmcur].style = polylinestyles[polylinestyles.length-1].name;
            placemarks[plmcur].stylecur = polylinestyles.length-1;
        //}
        preparePolyline();
        directionsintroduction();
        codeID = gob('codechoice').value = 1;
    }
    kmlcode = "";
    javacode = "";
}

function deleteLastPoint(){
	if(editing == true){
        stopediting();
    }
    if(polyPoints.length < 2) return;
    if(directionsYes == 1) {
        if(destinations.length == 1) return;
        undo();
        return;
    }
    if(toolID == 1) {
        if(polyShape) {
            polyPoints = polyShape.getPath();
            if(polyPoints.length > 0) {
                polyPoints.removeAt(polyPoints.length-1);
                pointsArrayKml.pop();
                if(codeID == 1) logCode1();
                if(codeID == 2) logCode4();
            }
        }
    }
    if(toolID == 2) {
        if(innerArrayKml.length>0) {
            innerArrayKml.pop();
            polyPoints.removeAt(polyPoints.length-1);
        }
        if(outerArrayKml.length>0 && innerArrayKml.length==0) {
            outerArrayKml.pop();
            //polyPoints.removeAt(polyPoints.length-1);
        }
        if(outerPoints.length===0) {
            if(polyShape) {
                polyPoints = polyShape.getPath();
                if(polyPoints.length > 0) {
                    polyPoints.removeAt(polyPoints.length-1);
                    pointsArrayKml.pop();
                    if(adder == 0) {
                        if(codeID == 1) logCode2();
                        if(codeID == 2) logCode4();
                    }
                }
            }
        }
    }
    if(polyPoints.length === 0) nextshape();
}
function counter(num){
    return adder = adder + num;
}
function stopediting(){
    editing = false;
    gob('EditButton').value = 'Edit lines';
    //closethis('RegretButton');
    if(outerArray.length > 0) {
        polyShape.setEditable(false);
        outerArray = [];
        outerArrayKml = [];
        innerArray = [];
        innerArrays = [];
        innerArrayKml = [];
        innerArraysKml = [];
        var polly = polyShape.getPaths();
        polyPoints = polly.getAt(0);
        var points = polly.getAt(0);
        //alert(point.lng().toFixed(6));
        for(var i = 0; i<points.length-1; i++) {
            outerArray.push(points.getAt(i).lat().toFixed(6) + ',' + points.getAt(i).lng().toFixed(6));
            outerArrayKml.push(points.getAt(i).lng().toFixed(6) + ',' + points.getAt(i).lat().toFixed(6));
        }
        for(i = 1; i<polly.length; i++) {
            points = polly.getAt(i);
            if(i == polly.length-1) {
                for(var j = 0; j<points.length; j++) {
                    innerArray.push(points.getAt(j).lat().toFixed(6) + ',' + points.getAt(j).lng().toFixed(6));
                    innerArrayKml.push(points.getAt(j).lng().toFixed(6) + ',' + points.getAt(j).lat().toFixed(6));
                }
            }else{
                for(var j = 0; j<points.length-1; j++) {
                    innerArray.push(points.getAt(j).lat().toFixed(6) + ',' + points.getAt(j).lng().toFixed(6));
                    innerArrayKml.push(points.getAt(j).lng().toFixed(6) + ',' + points.getAt(j).lat().toFixed(6));
                }
            }
            innerArrays.push(innerArray);
            innerArraysKml.push(innerArrayKml);
            innerArray = [];
            innerArrayKml = [];
        }
        toolID = 2;
        //closethis('polygonstuff');
        pcur = placemarks[plmcur].stylecur;
        //if(codeID == 1) logCode3();
        //if(codeID == 2) logCode5(); // write Google javascript
    }else{
        for(var i = 0; i < markers.length; i++) {
            markers[i].setMap(null);
        }
        for(var i = 0; i < midmarkers.length; i++) {
            midmarkers[i].setMap(null);
        }
        polyPoints = polyShape.getPath();
        markers = [];
        midmarkers = [];
        if(plmcur != placemarks.length-1) {
            placemarks[plmcur].shape = polyShape;
            drawnShapes.push(polyShape);
            addpolyShapelistener();
        }
        //setstartMarker(polyPoints.getAt(0));
    }
}
// the "Edit lines" button has been pressed
function editlines(){
    if(editing == true){
        stopediting();
    }else{
        if(outerArray.length > 0) {
            polyShape.setEditable(true);
            closethis('polygonstuff');
        }else{
            //polyPoints = polyShape.getPath();
            if(polyPoints.length > 0){
                //showthis('RegretButton');
                toolID = 1; // editing is set to be possible only in polyline draw mode
                setTool();
                if(startMarker) startMarker.setMap(null);
                /*polyShape.setOptions({
                    editable: true
                });*/
                for(var i = 0; i < polyPoints.length; i++) {
                    var marker = setmarkers(polyPoints.getAt(i));
                    markers.push(marker);
                    if(i > 0) {
                        var previous = polyPoints.getAt(i-1);
                        var midmarker = setmidmarkers(polyPoints.getAt(i),previous);
                        midmarkers.push(midmarker);
                    }
                }
            }
        }
        editing = true;
        gob('EditButton').value = 'Stop edit';
    }
}

function save(){
	if(polyPoints.length < 2)alert("Keine Strecke eingezeichnet");
	else{
		var data = {};
		data.route = {};
		data.route.coordinate = [];
		for (var i = 0; i < polyPoints.length; i++) {
			data.route.coordinate[i] = {'lat': polyPoints.getAt(i).lat(), 'lng': polyPoints.getAt(i).lng()};
		}
		var jsonToSend = "routeFile="+JSON.stringify(data);
		
		var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
	    jax.open('POST','/blp2.0/index.php/route/newRoute');
	    jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	    jax.send(jsonToSend)
	   
	    jax.onreadystatechange = function(){ if(jax.readyState==4) {
	        if(jax.responseText.indexOf('bien')+1)alert('Updated');
	        else alert(jax.responseText)
	    }}
	}
	
}

function load_strecke(){
	 var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
    jax.open('GET','/blp2.0/index.php/route/loadRoute/13');
    jax.send('command=fetch');
    jax.onreadystatechange = function(){ 
    if(jax.readyState==4) {       
    
        try { 
    	 drawData(jax.responseText);
       }catch(e){ 
    	   alert(e); 
    	 }
      }}
	
	
	
}

function drawData(json_laod){
	var newjson = eval('(' + json_laod + ')');
	//clearMap();
	for (var i = 0; i < newjson.route.coordinate.length; i++) {
		var point = new google.maps.LatLng(newjson.route.coordinate[i].lat,newjson.route.coordinate[i].lng);
		addLatLng(point);
	}
}

function clearMap(){
    if(editing == true) stopediting();
    if(polyShape) polyShape.setMap(null); // polyline or polygon
    if(outerShape) outerShape.setMap(null);
    if(rectangle) rectangle.setMap(null);
    if(circle) circle.setMap(null);
    if(drawnShapes.length > 0) {
        for(var i = 0; i < drawnShapes.length; i++) {
            drawnShapes[i].setMap(null);
        }
    }
    plmcur = 0;
    dirmarknum = 1;
    newstart();
    placemarks = [];
    createplacemarkobject();
}

// Called from editlines and listener set in setmidmarkers
function setmarkers(point) {
    var marker = new google.maps.Marker({
    	position: point,
    	map: map,
    	icon: imageNormal,
        raiseOnDrag: false,
    	draggable: true
    });
    google.maps.event.addListener(marker, "mouseover", function() {
    	marker.setIcon(imageHover);
    });
    google.maps.event.addListener(marker, "mouseout", function() {
    	marker.setIcon(imageNormal);
    });
    google.maps.event.addListener(marker, "drag", function() {
        for (var i = 0; i < markers.length; i++) {
            if (markers[i] == marker) {
                prevpoint = marker.getPosition();
                prevnumber = i;
                polyShape.getPath().setAt(i, marker.getPosition());
                movemidmarker(i);
                break;
            }
        }
        polyPoints = polyShape.getPath();
        var stringtobesaved = marker.getPosition().lat().toFixed(6) + ',' + marker.getPosition().lng().toFixed(6);
        var kmlstringtobesaved = marker.getPosition().lng().toFixed(6) + ',' + marker.getPosition().lat().toFixed(6);
        pointsArray.splice(i,1,stringtobesaved);
        pointsArrayKml.splice(i,1,kmlstringtobesaved);
        //logCode1();
    });
    google.maps.event.addListener(marker, "click", function() {
        for (var i = 0; i < markers.length; i++) {
            if (markers[i] == marker && markers.length != 1) {
                prevpoint = marker.getPosition();
                prevnumber = i;
                marker.setMap(null);
                markers.splice(i, 1);
                polyShape.getPath().removeAt(i);
                removemidmarker(i);
                break;
            }
        }
        polyPoints = polyShape.getPath();
        if(markers.length > 0) {
            pointsArray.splice(i,1);
            pointsArrayKml.splice(i,1);
            //logCode1();
        }
    });
    return marker;
}
// Called from editlines and listener set in this function
function setmidmarkers(point,prevpoint) {
    //var prevpoint = markers[markers.length-2].getPosition();
    var marker = new google.maps.Marker({
    	position: new google.maps.LatLng(
    		point.lat() - (0.5 * (point.lat() - prevpoint.lat())),
    		point.lng() - (0.5 * (point.lng() - prevpoint.lng()))
    	),
    	map: map,
    	icon: imageNormalMidpoint,
        raiseOnDrag: false,
    	draggable: true
    });
    google.maps.event.addListener(marker, "mouseover", function() {
    	marker.setIcon(imageHover);
    });
    google.maps.event.addListener(marker, "mouseout", function() {
    	marker.setIcon(imageNormalMidpoint);
    });
    google.maps.event.addListener(marker, "dragstart", function() {
    	for (var i = 0; i < midmarkers.length; i++) {
    		if (midmarkers[i] == marker) {
    			var tmpPath = tmpPolyLine.getPath();
    			tmpPath.push(markers[i].getPosition());
    			tmpPath.push(midmarkers[i].getPosition());
    			tmpPath.push(markers[i+1].getPosition());
    			break;
    		}
    	}
    });
    google.maps.event.addListener(marker, "drag", function() {
    	for (var i = 0; i < midmarkers.length; i++) {
    		if (midmarkers[i] == marker) {
    			tmpPolyLine.getPath().setAt(1, marker.getPosition());
    			break;
    		}
    	}
    });
    google.maps.event.addListener(marker, "dragend", function() {
    	for (var i = 0; i < midmarkers.length; i++) {
    		if (midmarkers[i] == marker) {
    			var newpos = marker.getPosition();
    			var startMarkerPos = markers[i].getPosition();
    			var firstVPos = new google.maps.LatLng(
    				newpos.lat() - (0.5 * (newpos.lat() - startMarkerPos.lat())),
    				newpos.lng() - (0.5 * (newpos.lng() - startMarkerPos.lng()))
    			);
    			var endMarkerPos = markers[i+1].getPosition();
    			var secondVPos = new google.maps.LatLng(
    				newpos.lat() - (0.5 * (newpos.lat() - endMarkerPos.lat())),
    				newpos.lng() - (0.5 * (newpos.lng() - endMarkerPos.lng()))
    			);
    			var newVMarker = setmidmarkers(secondVPos,startMarkerPos);
    			newVMarker.setPosition(secondVPos);//apply the correct position to the midmarker
    			var newMarker = setmarkers(newpos);
    			markers.splice(i+1, 0, newMarker);
    			polyShape.getPath().insertAt(i+1, newpos);
    			marker.setPosition(firstVPos);
    			midmarkers.splice(i+1, 0, newVMarker);
    			tmpPolyLine.getPath().removeAt(2);
    			tmpPolyLine.getPath().removeAt(1);
    			tmpPolyLine.getPath().removeAt(0);
    			/*newpos = null;
    			startMarkerPos = null;
    			firstVPos = null;
    			endMarkerPos = null;
    			secondVPos = null;
    			newVMarker = null;
    			newMarker = null;*/
    			break;
    		}
    	}
        polyPoints = polyShape.getPath();
        var stringtobesaved = newpos.lat().toFixed(6) + ',' + newpos.lng().toFixed(6);
        var kmlstringtobesaved = newpos.lng().toFixed(6) + ',' + newpos.lat().toFixed(6);
        pointsArray.splice(i+1,0,stringtobesaved);
        pointsArrayKml.splice(i+1,0,kmlstringtobesaved);
        logCode1();
    });
    return marker;
}
// Called from listener set in setmarkers
function movemidmarker(index) {
    var newpos = markers[index].getPosition();
    if (index != 0) {
    	var prevpos = markers[index-1].getPosition();
    	midmarkers[index-1].setPosition(new google.maps.LatLng(
    		newpos.lat() - (0.5 * (newpos.lat() - prevpos.lat())),
    		newpos.lng() - (0.5 * (newpos.lng() - prevpos.lng()))
    	));
    	//prevpos = null;
    }
    if (index != markers.length - 1) {
    	var nextpos = markers[index+1].getPosition();
    	midmarkers[index].setPosition(new google.maps.LatLng(
    		newpos.lat() - (0.5 * (newpos.lat() - nextpos.lat())),
    		newpos.lng() - (0.5 * (newpos.lng() - nextpos.lng()))
    	));
    	//nextpos = null;
    }
    //newpos = null;
    //index = null;
}
// Called from listener set in setmarkers
function removemidmarker(index) {
    if (markers.length > 0) {//clicked marker has already been deleted
    	if (index != markers.length) {
    		midmarkers[index].setMap(null);
    		midmarkers.splice(index, 1);
    	} else {
    		midmarkers[index-1].setMap(null);
    		midmarkers.splice(index-1, 1);
    	}
    }
    if (index != 0 && index != markers.length) {
    	var prevpos = markers[index-1].getPosition();
    	var newpos = markers[index].getPosition();
    	midmarkers[index-1].setPosition(new google.maps.LatLng(
    		newpos.lat() - (0.5 * (newpos.lat() - prevpos.lat())),
    		newpos.lng() - (0.5 * (newpos.lng() - prevpos.lng()))
    	));
    	//prevpos = null;
    	//newpos = null;
    }
    //index = null;
}

function showAddress(address) {
    geocoder.geocode({'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var pos = results[0].geometry.location;
            map.setCenter(pos);
            if(directionsYes == 1) drawDirections(pos);
            if(toolID == 5) drawMarkers(pos);
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

//]]>
</script>

<style type="text/css">
* {margin:0;padding:0;border:0;outline:0}
BODY {
    font-family: "Trebuchet MS", Arial,Helvetica,Sans Serif;
    font-size: 10pt;
}
a  {
	text-decoration : none;
}
a:hover  {
	text-decoration: underline;
}
p {
    padding-bottom: 8px;
}
#coords1 {
    padding: 5px;
    font-weight: bold;
}
#presenter {
    opacity:0.7;
    filter:alpha(opacity=70);
    -ms-filter:”alpha(opacity=70)”;
    -moz-opacity:0.7;
    KHTMLOpacity: 0.7;
    MozOpacity: 0.7;
    -khtml-opacity:.70;
}
#buttonrow {
    position: absolute;
    top: 50px;
    left: 540px;
    width: 505px;
    height: 80px;
}
#presenter {
    position: absolute;
    top: 160px;
    left: 540px;
    width: 523px;
    height: 413px;
    border: 2px solid #ccc;
}
#header {
    position: absolute;
    top: 5px;
    left: 10px;
    width: 1020px;
    height: 40px;
    background-color: #ffffff;
}
#map_canvas {
    position: absolute;
    top: 50px;
    left: 0px;
    width: 530px;
    height: 530px;
    background-color: #ffffff;
}
#polygonstuff {
    position: absolute;
    top: 400px;
    left: 5px;
    width: 70px;
    height: 60px;
    background-color: #ff0000;
    color: #ffffff;
    visibility: hidden;
}
#title {
    background-color: transparent;
    width: 300px;
    float: left;
}
.choice {
    background-color: transparent;
    width: 100px;
    float: left;
}
h1 {
    font-size:25px;
    font-weight: bold;
    color: #ff0000;
    padding-top: 4px;
    padding-left: 10px;
    padding-bottom: 11px;
}
.topbutton {
    padding-top: 10px;
    padding-bottom: 10px;
    padding-left: 10px;
    float: left;
}
#googlead {
    margin: 0 auto;
    width: 800px;
    padding-top: 5px;
}
.clear {
	clear:both;
}
#content {
    margin: 10px
}
#polylineoptions {
    position: absolute;
    background-color: #ffffff;
    top: 200px;
    left: 560px;
    width: 260px;
    height: 210px;
    border: 2px solid #337EB7;
    visibility: hidden;
}
#polygonoptions {
    position: absolute;
    background-color: #ffffff;
    top: 200px;
    left: 560px;
    width: 260px;
    height: 255px;
    border: 2px solid #337EB7;
    visibility: hidden;
}
#rectang {
    position: absolute;
    background-color: #ffffff;
    top: 200px;
    left: 560px;
    width: 260px;
    height: 260px;
    border: 2px solid #337EB7;
    visibility: hidden;
}
#circleoptions {
    position: absolute;
    background-color: #ffffff;
    top: 200px;
    left: 560px;
    width: 260px;
    height: 260px;
    border: 2px solid #337EB7;
    visibility: hidden;
}
#markeroptions {
    width: 950px;
    height: 310px;
    background-color: #ffffff;
    margin: 2px 2px 2px 2px;
    padding: 8px;
    border: 1px solid #aaa;
    position: absolute;
    top: 45px;
    left: 10px;
    z-index:99999;
    visibility:hidden;
}
#directionstyles {
    position: absolute;
    background-color: #ffffff;
    top: 200px;
    left: 560px;
    width: 260px;
    height: 210px;
    border: 2px solid #337EB7;
    visibility: hidden;
}
#iconimages {
    width: 430px;
    height: 300px;
    background-color: #ffffff;
    margin: 2px 2px 2px 2px;
    padding: 8px;
    float: left;
}
#stylestext {
    width: 485px;
    height: 280px;
    background-color: #ffffff;
    margin: 0px 0px 2px 2px;
    padding: 5px;
    float: left;
}
#toppers {
    width: 405px;
    height: 300px;
    background-color: #ffffff;
    margin: 2px 2px 2px 2px;
    padding: 8px;
    position: absolute;
    top: 165px;
    left: 90px;
    z-index:99999;
    visibility:hidden;
}
#dirtoppers {
    width: 405px;
    height: 350px;
    background-color: #ffffff;
    margin: 2px 2px 2px 2px;
    padding: 8px;
    position: absolute;
    top: 165px;
    left: 90px;
    z-index:99999;
    visibility: hidden;
}
.styletitle {
    margin-left:5px;
    padding:0 3px 0 5px;
    font-weight:bold;
    background-color: #CCCCFF;
}
.closebutton {
    border:1px solid #000000;
    padding:1px 4px 1px 4px;
    margin:1px 3px 1px 0px;
    color:#ffffff;
    background-color: #337EB7;
}
#RegretButton {
    visibility: hidden;
}
.label {
	float: left;
	text-align: right;
	margin-right: 5px;
	width: 80px;
	padding-top: 5px;
}
.input {
    float: left;
	padding-left: 3px;
	width: 55px;
	margin: 3px 0px 0px 3px;
	border: 2px solid #ccc;
}
.inputlong {
    float: left;
	padding-left: 3px;
	width: 75px;
	margin: 3px 0px 0px 3px;
	border: 2px solid #ccc;
}
.oklink {
    margin-left: 25px;
    padding:0px 3px 0px 3px;
    background-color: #CCFF66;
    text-decoration: none;
}
#morelinks td {
    padding-right: 10px;
}
</style>
</head>

<body id="body" onload="initmap()">

<div id="map_canvas"></div>
<div id="buttonrow">
    <div class="topbutton">
        <input type="button" onclick="deleteLastPoint();" value="Delete Last Point"/>
    </div>
    <div class="topbutton">
        <input type="button" onclick="editlines();" value="Edit lines" id="EditButton"/>
    </div>
	<div class="topbutton">
        <input type="button" onclick="save();" value="Save" id="Save"/>
    </div>
    <form style="margin-right:5px" action="#" onsubmit="showAddress(this.address.value); return false">
    <input type="text" style="border: 1px solid #000000;" size="50" name="address" value="Karl Johans gate 37, 0162 Oslo, Norge" />
    <input type="submit" value="Search" />
    </form>
</div>
</body>
</html>
